package com.zhouyu.mybatisSpring;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//@Component
public class ZhouyuFactoryBean implements FactoryBean {

	private Class mapperInterface;


	public ZhouyuFactoryBean(Class mapperInterface) {
		this.mapperInterface = mapperInterface;
	}


	private SqlSession  sqlSession;

	//依赖注入
	//@Autowired  replaceBy  {beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);}
	public void setSqlSession(SqlSessionFactory sqlSessionFactory){
		//加这行代码，处理异常，Mybatis源码导致的
		sqlSessionFactory.getConfiguration().addMapper(mapperInterface);
		this.sqlSession=sqlSessionFactory.openSession();
	}


	@Override
	public Object getObject() throws Exception {

		//自定义的代理对象
//		Object proxyInstance = Proxy.newProxyInstance(ZhouyuFactoryBean.class.getClassLoader(), new Class[]{mapperInterface}, new InvocationHandler() {
//			@Override
//			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//				System.out.println(method.getName());
//				return null;
//			}
//		});

		//mybatis产生的代理对象
		Object proxyInstance = sqlSession.getMapper(mapperInterface);

		return proxyInstance;
	}

	@Override
	public Class<?> getObjectType() {
		return mapperInterface;
	}
}
